﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Xml;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace UCL.Powersource
{

    /// <summary>
    /// Generic extension methods used by the framework.
    /// </summary>
    public static class ExtensionMethods
    {
        /// <summary>
        /// Get's the name of the assemblyFile.
        /// </summary>
        /// <param name="assemblyFile">The assemblyFile.</param>
        /// <returns>The assemblyFile's name.</returns>
        public static string GetAssemblyName(this Assembly assembly)
        {
            return assembly.FullName.Remove(assembly.FullName.IndexOf(","));
        }

        /// <summary>
        /// Gets all the attributes of a particular type.
        /// </summary>
        /// <typeparam name="T">The type of attributes to get.</typeparam>
        /// <param name="member">The member to inspect for attributes.</param>
        /// <param name="inherit">Whether or not to search for inherited attributes.</param>
        /// <returns>The list of attributes found.</returns>
        public static IEnumerable<T> GetAttributes<T>(this MemberInfo member, bool inherit)
        {
#if WinRT
            return member.GetCustomAttributes(inherit).OfType<T>();
#else
            return Attribute.GetCustomAttributes(member, inherit).OfType<T>();
#endif
        }

        /// <summary>
        /// Applies the action to each element in the list.
        /// </summary>
        /// <typeparam name="T">The enumerable item's type.</typeparam>
        /// <param name="enumerable">The elements to enumerate.</param>
        /// <param name="action">The action to apply to each item in the list.</param>
        public static void Apply<T>(this IEnumerable<T> enumerable, Action<T> action)
        {
            foreach (var item in enumerable)
            {
                action(item);
            }
        }

        /// <summary>
        /// Converts an expression into a <see cref="MemberInfo"/>.
        /// </summary>
        /// <param name="expression">The expression to convert.</param>
        /// <returns>The member info.</returns>
        public static MemberInfo GetMemberInfo(this Expression expression)
        {
            var lambda = (LambdaExpression)expression;

            MemberExpression memberExpression;
            if (lambda.Body is UnaryExpression)
            {
                var unaryExpression = (UnaryExpression)lambda.Body;
                memberExpression = (MemberExpression)unaryExpression.Operand;
            }
            else
            {
                memberExpression = (MemberExpression)lambda.Body;
            }

            return memberExpression.Member;
        }




        public static void TraceMethod(this ILog Log)
        {
            var st = new StackTrace(1, true);
            var callingFunction = st.GetFrame(0);
            var mt = callingFunction.GetMethod().Name;
            var trace = string.Format("In {0} at line {2} of {1}", mt, callingFunction.GetFileName(), callingFunction.GetFileLineNumber());
            Log.Trace(trace);
        }

        public static void DebugMethod(this ILog Log)
        {
            var st = new StackTrace(1, true);
            var callingFunction = st.GetFrame(0);
            var mt = callingFunction.GetMethod().Name;
            var trace = string.Format("In {0} : {1}", mt);
            Log.Debug(trace);
        }

        public static void DebugMethod(this ILog Log, string format, params object[] args)
        {
            var st = new StackTrace(1, true);
            var callingFunction = st.GetFrame(0);
            var mt = callingFunction.GetMethod().Name;
            if (format == null) format = string.Empty;
            var str = string.Format(format, args);
            var trace = string.Format("In {0} : {1}", mt, str);
            Log.Debug(trace);
        }

        public static void TraceMethod(this ILog Log, string format, params object[] args)
        {
            var st = new StackTrace(1, true);
            var callingFunction = st.GetFrame(0);
            var mt = callingFunction.GetMethod().Name;
            var str = string.Format(format, args);
            var trace = string.Format("In {0} : {1}", mt, str);
            Log.Trace(trace);
        }


    }

}

namespace UCL.Powersource.TFS
{
    public static class ExtensionMethods
    {
        public static Project GetProject(this TfsTeamProjectCollection col, string Name)
        {
            var store = col.GetService<WorkItemStore>();
            foreach (Project pr in store.Projects)
            {
                if (pr.Name == Name) return pr;
            }
            return null;
        }

        public static Project GetProjectAtIndex(this TfsTeamProjectCollection col, int index)
        {
            var store = col.GetService<WorkItemStore>();
            foreach (Project pr in store.Projects)
            {
                if (index == 0) return pr; //store.Projects.
                index--;
            }
            return null;
        }
        //    /// <summary>
        //    /// http://blog.johnsworkshop.net/tfs11-api-managing-the-stat-iteration-schedule/
        //    /// http://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.server.nodeinfo.startdate(v=vs.110).aspx
        //    /// </summary>
        //    /// <param name="css"></param>
        //    /// <param name="projectUri"></param>
        //    /// <returns></returns>
        //    static IEnumerable<ScheduleInfo> GetIterationDates(this ICommonStructureService4 css, string projectUri)
        //    {
        //        NodeInfo[] structures = css.ListStructures(projectUri);

        //        NodeInfo iterations = structures.FirstOrDefault(n => n.StructureType.Equals("ProjectLifecycle"));
        //        List<ScheduleInfo> schedule = null; 
        //        if (iterations != null)
        //        {
        //            string projectName = css.GetProject(projectUri).Name;
        //            XmlElement iterationsTree = css.GetNodesXml(new[] { iterations.Uri }, true);
        //            GetIterationDates(iterationsTree.ChildNodes[0], projectName, ref schedule);
        //        } 
        //        return schedule;
        //    }

        //    private static void GetIterationDates(XmlNode node, string projectName, ref List<ScheduleInfo> schedule)
        //    {    
        //        if (schedule == null)   schedule = new List<ScheduleInfo>();     
        //        if (node != null)    
        //        {        
        //            string iterationPath = node.Attributes["Path"].Value;        
        //            if (!string.IsNullOrEmpty(iterationPath))        
        //            {            // Attempt to read the start and end dates if they exist.            
        //                string strStartDate = (node.Attributes["StartDate"] != null) ? node.Attributes["StartDate"].Value : null;            string strEndDate = (node.Attributes["FinishDate"] != null) ? node.Attributes["FinishDate"].Value : null;             DateTime? startDate = null, endDate = null;                         if (!string.IsNullOrEmpty(strStartDate) && !string.IsNullOrEmpty(strEndDate))            {                bool datesValid = true;                 // Both dates should be valid.                datesValid &= DateTime.TryParse(strStartDate, out startDate);                datesValid &= DateTime.TryParse(strEndDate, out endDate);                 // Clear the dates unless both are valid.                if (!datesValid)                {                    startDate = null,                    endDate = null;                }            }                         schedule.Add(new ScheduleInfo            {                Path = iterationPath.Replace(string.Concat("\\", projectName, "\\Iteration"), projectName),                StartDate = startDate,                EndDate = endDate                                   });        }         // Visit any child nodes (sub-iterations).        if (node.FirstChild != null)        {            // The first child node is the <Children> tag, which we'll skip.            for (int nChild = 0; nChild < node.ChildNodes[0].ChildNodes.Count; nChild++)                GetIterationDates(node.ChildNodes[0].ChildNodes[nChild], projectName, ref schedule);        }    }}
        //}
    }
}



